﻿/*

Flash CS4 ActionScript 3 Tutorial by Dan Gries.

www.flashandmath.com.

*/

package com.flashandmath.dg.objects {
	import flash.display.Sprite;
	import flash.geom.*;
	
	public class DiskParticle extends Sprite {
				
		public var lifespan:int;
						
		public var pos:Point;		
		public var lastPos:Point;
		public var vel:Point;
		public var accel:Point;
		
		public var color:uint;
		
		public var radiusWhenStill:Number;
		
		public var breakawayTime:Number;
		public var attack:Number;
		public var hold:Number;
		public var decay:Number;
		public var rInit:Number;
		public var rHold:Number;
		public var rLast:Number;
		
		//The following attributes are for the purposes of creating a
		//linked list of DiskParticle instances.
		public var next:DiskParticle;
		public var prev:DiskParticle;
		
		public var dotRadius:Number;
		public var dotRadiusVariance:Number;
		public var dead:Boolean;
		
		private var rad:Number;
		public var airResistanceFactor:Number;
		
		public function DiskParticle(x0=0,y0=0) {
			super();
			lastPos = new Point(x0,y0);
			pos = new Point(x0,y0);
			accel = new Point();
			vel = new Point();
			color = 0xDDDDDD;
			radiusWhenStill = 1.5;
			dotRadius = 1;
			dotRadiusVariance = 0;
			
			breakawayTime = 0;
			attack = 100+Math.random()*10;
			hold = 60+Math.random()*30;
			decay = 70+Math.random()*100;
			rInit = 0;
			rHold = 1.5;
			rLast = 0.5;
			
			airResistanceFactor = 0;
			
			dead = false;
		}
		
		public function setEnvelope(a:Number, h:Number, d:Number, av:Number, hv:Number, dv:Number, r0:Number, r1:Number, r2:Number, rv:Number):void {
			attack = a+(2*Math.random()-1)*av;
			hold = h+(2*Math.random()-1)*hv;
			decay = d+(2*Math.random()-1)*dv;
			rInit = r0;
			rHold = r1;
			rLast = r2;
			dotRadiusVariance = rv;
			rad = rInit;
		}
				
		public function resetPosition(x0=0,y0=0) {
			lastPos = new Point(x0,y0);
			pos = new Point(x0,y0);
		}
		
		public function redraw():void {
			this.graphics.clear();
			if (lifespan < breakawayTime) {
				this.graphics.beginFill(color);
				this.graphics.drawEllipse(pos.x-radiusWhenStill,pos.y-radiusWhenStill,2*radiusWhenStill,2*radiusWhenStill)
				this.graphics.endFill();
			}
			else {
				//dot:
				if (lifespan < breakawayTime+attack+hold+decay) {
					if (lifespan < breakawayTime+attack) {
						rad = (rHold - rInit)/attack*(lifespan-breakawayTime) + rInit;
					}
					else if (lifespan < breakawayTime+attack+hold) {
						rad = rHold;
					}
					else if (lifespan < breakawayTime+attack+hold+decay) {
						rad = (rLast - rHold)/decay*(lifespan-breakawayTime-attack-hold) + rHold;
					}
					rad = (1+dotRadiusVariance*(1-2*Math.random()))*rad;
					this.graphics.beginFill(color);
					this.graphics.drawEllipse(pos.x-rad,pos.y-rad,2*rad,2*rad);
					this.graphics.endFill();
					
				}
				else {
					dead = true;
				}				
			}
		}
		
	}
}
			
		